package com.sky.Protocol;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

import java.nio.ByteOrder;
import java.util.List;

/**
 * Created by sun on 2017-06-11.
 */
//public class MessageDecoder extends ByteToMessageDecoder {
//
//    public final int HEADER_LENGTH = MessageHeader.HEADER_LENGTH;
//
//    @Override
//    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
//        if(byteBuf.readableBytes() >= HEADER_LENGTH) {
//
//            byteBuf.markReaderIndex();
//
//            /**
//             * 读取body长度
//             */
//            int length = byteBuf.readInt();
//
//            /**
//             * 判断是否是完整的包
//             */
//            if(byteBuf.readableBytes() < length + HEADER_LENGTH) {
//                //包不完整，还原
//                byteBuf.resetReaderIndex();
//                return ;
//            }
//
//            byte[] headerData = new byte[HEADER_LENGTH];
//            byteBuf.readBytes(headerData);
//
//            byte[] bodyData = new byte[length];
//            byteBuf.readBytes(bodyData);
//
//            MessageProtocol messageProtocol = new MessageProtocol(length,headerData,bodyData);
//            list.add(messageProtocol);
//        }
//    }
//}


public class MessageDecoder extends LengthFieldBasedFrameDecoder {

    public static final int HEADER_LENGTH = MessageHeader.HEADER_LENGTH;

    public MessageDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment, int initialBytesToStrip, boolean failFast) {
        super(maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment, initialBytesToStrip, failFast);
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        if(in == null) {
            return null;
        }

        ByteBuf buf = (ByteBuf)super.decode(ctx,in);
        if(buf == null) {
            return null;
        }

        int t = buf.readableBytes();

        if(t < HEADER_LENGTH) {
            throw new Exception("length less then head1!");
        }

        int length = buf.readInt();

        t = buf.readableBytes();

        if(t < length) {
//            throw new Exception("length less then head!");
            return null;
        }

        byte[] headerData = new byte[HEADER_LENGTH];
        buf.readBytes(headerData);

        byte[] bodyData = new byte[length - HEADER_LENGTH];
        buf.readBytes(bodyData);

        MessageProtocol messageProtocol = new MessageProtocol(length,headerData,bodyData);

        return messageProtocol;
    }

}
